/**
 * @Title: LogAspect.java
 * @Package com.ndmicro.tmd.web.aop
 * @author roc
 * @date 2020年3月10日 下午2:48:46
 * @version V1.0
 * @copyright ndmicro
 */
package cn.cqie.frame.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author roc
 * @ClassName: LogAspect
 * @Description: 接口请求日志
 * @date 2020年3月10日 下午2:48:46
 */
@Aspect
@Component
@Order(8)
@Slf4j
public class LogAspectPrint {
    @Pointcut("execution(* cn.cqie.frame.controller..*.*(..))" +
            "||execution(* cn.cqie.frame.*.impl..*.*(..))")
    private void aspect() {
    }

    @Around("aspect()")
    public Object around(JoinPoint joinPoint) throws Throwable {

        long timeMillis = System.currentTimeMillis();
        ProceedingJoinPoint proceedingJoinPoint = (ProceedingJoinPoint) joinPoint;
        Class clazz = proceedingJoinPoint.getTarget().getClass();
        String className = clazz.getName();
        String methodName = proceedingJoinPoint.getSignature().getName();
        Object[] objects = joinPoint.getArgs();

        // 将参数所在的数组转换成json
        Object[] arguments = new Object[objects.length];
        for (int i = 0; i < objects.length; i++) {
            if (objects[i] instanceof ServletRequest || objects[i] instanceof ServletResponse
                    || objects[i] instanceof MultipartFile) {
                continue;
            }
            arguments[i] = objects[i];
        }
        try {

            if (arguments != null && arguments.length > 0) {
                log.info("时间戳：{}，className-->:{},methodName-->:{},参数:{}", timeMillis, className, methodName, JSONObject.toJSONString(arguments));
            } else {
                log.info("时间戳：{}，className-->:{},methodName-->:{},无参数", timeMillis, className, methodName);
            }
        } catch (Exception e) {
            // 日志不能影响业务
        }
        long start = System.currentTimeMillis();
        Object result = ((ProceedingJoinPoint) joinPoint).proceed();
        long useTime = System.currentTimeMillis() - start;
        try {
            if (result == null) {
                log.info("时间戳：{}，className-->:{},methodName-->:{},耗时:{},无返回值", timeMillis, className, methodName, useTime);
            } else {
                log.info("时间戳：{}，className-->:{},methodName-->:{},耗时:{},返回值:{}", timeMillis, className, methodName, useTime, JSONObject.toJSONString(result));
            }
        } catch (Exception e) {
            // 日志不能影响业务
        }
        return result;
    }
}
